// ==UserScript==
// @name         一键解析
// @namespace    http://tampermonkey.net/
// @version      1.2.0
// @description  啦啦啦
// @author       King
// @license      MIT
// @match        *://*.youku.com/*
// @match        *://*.iqiyi.com/*
// @match        *://*.le.com/*
// @match        *://*.v.qq.com/*
// @match        *://*.mgtv.com/*
// @match        *://*.bilibili.com/*
// @grant        GM_addStyle
// @grant        GM_openInTab
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        unsafeWindow
// @updateURL  https://gitee.com/kingstk/script/raw/master/vip-video.meta.js
// @downloadURL  https://gitee.com/kingstk/script/raw/master/vip-video.user.js
// ==/UserScript==

(function () {
  "use strict";

  const parseInterfaces = [
    { name: "视频1", url: "https://jx.xmflv.com/?url=" },
    { name: "视频2", url: "https://jx.playerjy.com/?url=" },
    { name: "视频3", url: "https://jx.m3u8.tv/jiexi/?url=" },
    { name: "视频4", url: "https://jx.mmkv.cn/tv.php?url=" },
    { name: "视频5", url: "https://www.yemu.xyz/v/d.php?url=" },
  ];

  let currentInterfaceIndex = GM_getValue("currentInterfaceIndex", 0);

  function addParseButton() {
    GM_addStyle(`
      #vipPanelContainer {
        position: fixed;
        top: 10px;
        right: 10px;
        z-index: 9999;
        background-color: white;
        border: 1px solid #ccc;
        border-radius: 8px;
        padding: 15px;
        box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.1);
        text-align: center;
      }
      #vipPanelTitle {
        font-size: 18px;
        font-weight: bold;
        margin-bottom: 10px;
        color: #333;
      }
      #parseButton, #switchButton {
        display: block;
        width: calc(100% - 20px);
        margin: 5px 10px;
        padding: 10px;
        color: white;
        cursor: pointer;
        border-radius: 6px;
        transition: opacity 0.3s ease;
        border: none;
        font-size: 14px;
        outline: none;
      }
      #parseButton {
        background-color: #5cb85c;
      }
      #switchButton {
        background-color: #f0ad4e;
      }
      #switchButton span {
        display: block;
        font-size: 11px;
        margin-top: 3px;
        opacity: 0.8;
      }
      #parseButton:hover, #switchButton:hover {
        opacity: 0.85;
      }
    `);

    const panelContainer = document.createElement("div");
    panelContainer.id = "vipPanelContainer";
    document.body.appendChild(panelContainer);

    const panelHeader = document.createElement("div");
    panelHeader.style.cssText = 'display: flex; align-items: center; justify-content: space-between; cursor: move; padding: 5px;';
    panelContainer.appendChild(panelHeader);

    const panelTitle = document.createElement("h3");
    panelTitle.id = "vipPanelTitle";
    panelTitle.textContent = "VIP解析";
    panelHeader.appendChild(panelTitle);

    const collapseButton = document.createElement("button");
    collapseButton.id = "collapseButton";
    collapseButton.textContent = "-"; // 初始显示为缩小按钮
    collapseButton.style.cssText = 'background: none; border: none; color: #666; font-size: 16px; cursor: pointer;';
    panelHeader.appendChild(collapseButton);

    let isCollapsed = false;
    const buttonContainer = document.createElement("div");
    buttonContainer.id = "buttonContainer";
    panelContainer.appendChild(buttonContainer);

    GM_addStyle(`
      #buttonContainer {
        transition: max-height 0.3s ease-in-out;
        overflow: hidden;
      }
    `);

    collapseButton.addEventListener('click', function() {
      isCollapsed = !isCollapsed;
      if (isCollapsed) {
        buttonContainer.style.maxHeight = '0px';
        collapseButton.textContent = "+"; // 切换为放大按钮
        panelContainer.style.width = 'auto';
        panelContainer.style.padding = '5px';
        panelTitle.style.fontSize = '12px';
        // 自动靠边
        if (panelContainer.offsetLeft + panelContainer.offsetWidth / 2 < window.innerWidth / 2) {
          panelContainer.style.left = '0px';
          panelContainer.style.right = 'auto';
        } else {
          panelContainer.style.right = '0px';
          panelContainer.style.left = 'auto';
        }
      } else {
        buttonContainer.style.maxHeight = '200px'; // 假设按钮区域最大高度
        collapseButton.textContent = "-"; // 切换为缩小按钮
        panelContainer.style.width = '200px';
        panelContainer.style.padding = '15px';
        panelTitle.style.fontSize = '18px';
      }
    });

    // 初始状态设置为缩小
    isCollapsed = true;
    buttonContainer.style.maxHeight = '0px';
    collapseButton.textContent = "+";
    panelContainer.style.width = 'auto';
    panelContainer.style.padding = '5px';
    panelContainer.style.right = '0px';
    panelTitle.style.fontSize = '12px';

    GM_addStyle(`
      #vipPanelContainer {
        position: fixed;
        top: 10px;
        right: 10px;
        z-index: 9999;
        background-color: white;
        border: 1px solid #ccc;
        border-radius: 8px;
        padding: 5px;
        box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.1);
        text-align: center;
        width: auto;
        transition: all 0.3s ease-in-out;
      }
      #vipPanelTitle {
        font-size: 18px;
        font-weight: bold;
        margin: 0;
        padding: 5px;
        color: #333;
        cursor: move;
      }
      #parseButton, #switchButton {
        display: block;
        width: calc(100% - 20px);
        margin: 5px 10px;
        padding: 10px;
        color: white;
        cursor: pointer;
        border-radius: 6px;
        transition: opacity 0.3s ease;
        border: none;
        font-size: 14px;
        outline: none;
      }
      #parseButton {
        background-color: #5cb85c;
      }
      #switchButton {
        background-color: #f0ad4e;
      }
      #switchButton span {
        display: block;
        font-size: 11px;
        margin-top: 3px;
        opacity: 0.8;
      }
      #parseButton:hover, #switchButton:hover {
        opacity: 0.85;
      }
    `);

    const parseButton = document.createElement("button");
    parseButton.id = "parseButton";
    parseButton.textContent = "一键解析";
    buttonContainer.appendChild(parseButton);

    const switchButton = document.createElement("button");
    switchButton.id = "switchButton";
    switchButton.innerHTML = `切换接口<br><span>(${parseInterfaces[currentInterfaceIndex].name})</span>`;
    buttonContainer.appendChild(switchButton);

    parseButton.addEventListener("click", function () {
      const currentUrl = window.location.href;
      const parseUrl =
        parseInterfaces[currentInterfaceIndex].url +
        encodeURIComponent(currentUrl);
      GM_openInTab(parseUrl, { active: true, insert: true, setParent: true });
    });

    switchButton.addEventListener("click", function () {
      currentInterfaceIndex =
        (currentInterfaceIndex + 1) % parseInterfaces.length;
      GM_setValue("currentInterfaceIndex", currentInterfaceIndex);
      switchButton.innerHTML = `切换接口<br><span>(${parseInterfaces[currentInterfaceIndex].name})</span>`;
    });

    // 使面板可以吸附在屏幕两侧
    panelHeader.addEventListener('mousedown', startDrag);

    let offsetX, offsetY;
    let isDragging = false;

    function startDrag(e) {
      e.preventDefault(); // 阻止默认的拖动行为，避免选择文本
      isDragging = true;
      // 确保 offset 是相对于鼠标点击时面板的位置计算的
      offsetX = e.clientX - panelContainer.getBoundingClientRect().left;
      offsetY = e.clientY - panelContainer.getBoundingClientRect().top;
      panelHeader.style.userSelect = 'none'; // 禁止文本选择
      panelContainer.style.transition = 'none'; // 移除过渡动画
      document.addEventListener('mousemove', dragPanel);
      document.addEventListener('mouseup', stopDrag);
    }

    function dragPanel(e) {
      if (!isDragging) return;
      const newLeft = e.clientX - offsetX;
      const newTop = e.clientY - offsetY;

      // 获取浏览器可视区域尺寸
      const windowWidth = window.innerWidth;
      const windowHeight = window.innerHeight;

      // 获取面板尺寸
      const panelWidth = panelContainer.offsetWidth;
      const panelHeight = panelContainer.offsetHeight;

      // 计算允许的拖动范围
      const minLeft = 0;
      const maxLeft = windowWidth - panelWidth;
      const minTop = 0;
      const maxTop = windowHeight - panelHeight;

      // 限制拖动范围
      panelContainer.style.left = Math.min(maxLeft, Math.max(minLeft, newLeft)) + 'px';
      panelContainer.style.top = Math.min(maxTop, Math.max(minTop, newTop)) + 'px';
    }

    function stopDrag() {
      isDragging = false;
      panelHeader.style.userSelect = ''; // 恢复文本选择
      panelContainer.style.transition = ''; // 恢复过渡动画
      document.removeEventListener('mousemove', dragPanel);
      document.removeEventListener('mouseup', stopDrag);
    }
  }

  function handleParsePage() {
    let attempts = 0;
    const maxAttempts = 10;

    function attemptPlay() {
      attempts++;
      console.log(`尝试播放，第 ${attempts} 次`);

      const playButtons = document.querySelectorAll(
        "button, .button, .play-button, .xgplayer-play"
      );
      playButtons.forEach((button, index) => {
        if (button.offsetParent !== null) {
          button.click();
          console.log(`点击了第 ${index + 1} 个可能的播放按钮`);
        }
      });

      const isPlaying = Array.from(document.querySelectorAll("video")).some(
        (video) => !video.paused
      );
      if (isPlaying) {
        console.log("视频已开始播放，停止尝试");
        return;
      }

      if (attempts < maxAttempts) {
        setTimeout(attemptPlay, 1000);
      } else {
        console.log("达到最大尝试次数，停止尝试");
      }
    }

    window.addEventListener("load", function () {
      console.log("页面加载完成，2秒后开始尝试播放");
      setTimeout(attemptPlay, 2000);
    });
  }

  let isParsePage = false;
  for (let i = 0; i < parseInterfaces.length; i++) {
    if (window.location.href.startsWith(parseInterfaces[i].url)) {
      isParsePage = true;
      break;
    }
  }

  if (isParsePage) {
    handleParsePage();
  } else {
    addParseButton();
  }
})();
